require('dotenv').config();
const express = require('express');
const cors = require('cors');
// 初始化Express应用
const app = express();
const port = 3010;
// 原代码顶部添加以下内容
const http = require('http');
const socketIo = require('socket.io');
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "http://localhost:9000",
    methods: ["GET", "POST"]
  }
});
app.set('io', io);



// 中间件配置
app.use(cors({
  origin: 'http://localhost:9000',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json({
  limit: '50mb',
  verify: (req, res, buf) => {
    // 捕获解析异常
    try {
      JSON.parse(buf.toString());
    } catch (e) {
      throw new Error('Invalid JSON');
    }
  }
}));

// 设置表单请求体上限为50MB
app.use(express.urlencoded({
  limit: '50mb',
  extended: true
}));

// 引入路由模块
const authRoutes = require('./routes/auth');
const smsRoutes = require('./routes/sms');
const userRoutes = require('./routes/user');
const recordsRoutes = require('./routes/books');
const commentRoutes = require('./routes/comment');
const commentLikesRoutes = require('./routes/comment_likes');
const commentChildRoutes = require('./routes/comment_child');
const familyRoutes = require('./routes/family');
const chatMsgRoutes = require('./routes/chat');

// 挂载路由
app.use('/', authRoutes);
app.use('/', smsRoutes);
app.use('/', userRoutes);
app.use('/', recordsRoutes);
app.use('/', commentRoutes);
app.use('/', commentLikesRoutes);
app.use('/', commentChildRoutes);
app.use('/', familyRoutes);
app.use('/', chatMsgRoutes);
app.use('/uploads', express.static('public/uploads'));

// 启动服务器
server.listen(port, () => {
  console.log(`服务器在 http://localhost:${port} 启动`);
});
app.listen(port, () => {
  console.log(`服务器在 http://localhost:${port} 启动`);
});